<template>
  <view class="upload">
    <view
        v-for="(item,index) in data"
        :key="index"
        class="upload-img"
        @click="preview(value,index,'id')"
    >
      <l-image :width="width" :height="width" :src="item.id"/>
      <view class="iconfont" v-if="!disabled" @click.stop="deleteImg(index)">
        <u-icon name="close-circle"></u-icon>
      </view>
    </view>
    <view
        class="upload-button"
        :style="{width:width,height:width}"
        @click="handleUpLoad()"
        v-if="!disabled&&maxNum>data.length"
    >
      <slot name="add">
        <text class="iconfont icon-plus"></text>
        <text>添加图片</text>
      </slot>
    </view>
  </view>
</template>

<script>
import {chooseAndUpload, preview} from "@/utils/File";

export default {
  name: "l-upload",
  props: {
    value: {
      required: true
    },
    btype: {
      type: String,
    },
    width: {
      type: String,
      default: "160rpx"
    },
    maxNum: {
      type: Number,
      default: 3
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    data() {
      if (typeof this.value === 'string') {
        return this.value.split(',').map(item => {
          return {id: item}
        });
      }
      if (typeof this.value === 'undefined') {
        return []
      }
      return this.value
    }
  },
  methods: {
    preview,
    async handleUpLoad() {
      const res = await chooseAndUpload(this.data.length, this.btype, this.maxNum,);
      this.$emit('input', this.data.concat(res));
    },
    /** 清除 附件 */
    deleteImg(index) {
      const data = JSON.parse(JSON.stringify(this.data));
      data.splice(index, 1)
      this.$emit('input', data);
    },
  }
}
</script>


<style scoped lang="scss">
$upload-bg:$bg-main;
$upload-close-color:$color-main;
$upload-hint-color:$color-hint;
$upload-hint-font:$font-hint;

.upload {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;

  &-button {
    background-color: $upload-bg;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color:$upload-hint-color;
    font-size: $upload-hint-font;

    .iconfont {
      font-size: 48rpx;
      margin-bottom: 16rpx;
    }
  }
}

.upload-img {
  position: relative;

  .iconfont {
    position: absolute;
    top: -15rpx;
    right: -15rpx;
    font-size: 32rpx;
    color: $upload-close-color;
  }
}
</style>
